package com.ssh.manager.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.ssh.common.log.LogFactory;
import com.ssh.common.log.LogName;
import com.ssh.common.util.Page;
import com.ssh.dao.IDao;
import com.ssh.entity.Brand;
import com.ssh.entity.ChangGui;
import com.ssh.entity.Company;
import com.ssh.entity.HelpSale;
import com.ssh.entity.Product;
import com.ssh.entity.SuperMarket;
import com.ssh.entity.Task;
import com.ssh.entity.TaskBrand;
import com.ssh.entity.TaskProductEmployee;
import com.ssh.manager.TaskProductEmployeeManager;
import com.sun.org.apache.xpath.internal.operations.Bool;

@Service
public class TaskProductEmployeeManagerImpl implements TaskProductEmployeeManager{

	@Resource
	private IDao daoImpl;

	@Override
	public boolean delete(Long id) {
		try {
			TaskProductEmployee tpe = daoImpl.getDomain(TaskProductEmployee.class, id);
			//查询同一个任务品牌下的分配任务数量，如果为最后一条，则删除任务品牌数据
			TaskBrand tb = tpe.getTaskBrand();
			String sql = "select count(*) from TaskProductEmployee where del!=1 and taskBrand.id=?";
			int sum = daoImpl.countAll(sql, new Object[]{tb.getId()});
			if (sum<=1) {
				tb.setDel(1);
				daoImpl.saveOrUpdateDomain(tb);
			}
			tpe.setDel(1);
			daoImpl.saveOrUpdateDomain(tpe);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public void findListBy(Map conditionMap, Page page, String isDesc) {
		String sql = "select count(*) from TaskProductEmployee where del!=1";
		String listSql = "from TaskProductEmployee where del!=1";
		if(conditionMap.get("task")!=null && !conditionMap.get("task").equals("")){
			sql += " and taskBrand.task.content like '%"+conditionMap.get("task")+"%'";
			listSql += " and taskBrand.task.content like '%"+conditionMap.get("task")+"%'";
		}
		if(conditionMap.get("employee")!=null && !conditionMap.get("employee").equals("")){
			sql += " and employee.id="+conditionMap.get("employee");
			listSql += " and employee.id="+conditionMap.get("employee");
		}
		if(conditionMap.get("market")!=null && !conditionMap.get("market").equals("")){
			sql += " and superMarketProduct.superMarket.name like '%"+conditionMap.get("market")+"%'";
			listSql += " and superMarketProduct.superMarket.name like '%"+conditionMap.get("market")+"%'";
		}
		if(conditionMap.get("brand")!=null && !conditionMap.get("brand").equals("")){
			sql += " and taskBrand.brand.id="+conditionMap.get("brand");
			listSql += " and taskBrand.brand.id="+conditionMap.get("brand");
		}
		if(conditionMap.get("product")!=null && !conditionMap.get("product").equals("")){
			sql += " and superMarketProduct.product.id="+conditionMap.get("product");
			listSql += " and superMarketProduct.product.id="+conditionMap.get("product");
		}
		int sum = daoImpl.countAll(sql, null);
		page.setTotalCount(new Long(sum));
		page.countTotalPageNum();
		
		listSql += " order by createDate "+isDesc;
		List<TaskProductEmployee> tpe = (List<TaskProductEmployee>)daoImpl.findListBySql(listSql, new Object[]{}, false, true, false, page.getNumberPerPage()*(page.getCurPageNum()-1), page.getNumberPerPage());
		page.setPageData(tpe);
	}

	@Override
	public TaskProductEmployee saveUpdate(
			TaskProductEmployee taskProductEmployee) {
		return daoImpl.saveOrUpdateDomain(taskProductEmployee);
	}

	@Override
	public Map<String, Object> LastTask(long employeeId) {
		List<Object[]> list= (List<Object[]>)daoImpl.findListBySql("select taskBrand.task.id,taskBrand.task.content,taskBrand.task.id.createDate from  TaskProductEmployee where employee.id=? and del=? and employee.del=0  order by createDate desc", new Object[]{employeeId,0}, false, true, false, 0, 1);
    if (list!=null&&list.size()>0) {
	  Map<String, Object> task=new HashMap<String, Object>(); 
	  task.put("id", list.get(0)[0]);
	  task.put("name", list.get(0)[1]);
	  
	  SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd"); //格式化当前系统日期
	  String dateTime = dateFm.format(list.get(0)[2]);
	  task.put("createDate",dateTime);
	  return task;
    }
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Company> companyListFromTask(Long taskId, long employeeId) {
		List<Object[]> list= (List<Object[]>)daoImpl.findListBySql("select superMarketProduct.superMarket.company.id,superMarketProduct.superMarket.company.name from  TaskProductEmployee where employee.id=? and taskBrand.task.id=? and del=? and employee.del=0  group by superMarketProduct.superMarket.company.id order by superMarketProduct.superMarket.company.createDate desc", new Object[]{employeeId,taskId,0}, false, true, false, 0, -1);
		  List<Company> list2=new ArrayList<Company>();
		  for(Object[] obj : list){
			  Company company=new Company();
			  company.setId(Long.parseLong(obj[0].toString()));
			  company.setName((String)obj[1]);
			  list2.add(company);
		  }
		return list2;
	}

	@Override
	public List<SuperMarket> superMarketListFromTaskAndCompany(long taskId,
			Long companyId, long employeeId) {
		// TODO Auto-generated method stub
		List<Object[]> list= (List<Object[]>)daoImpl.findListBySql("select superMarketProduct.superMarket.id,superMarketProduct.superMarket.name from  TaskProductEmployee where employee.id=? and superMarketProduct.superMarket.company.id=? and taskBrand.task.id=? and del=? and employee.del=0  group by superMarketProduct.superMarket.id order by superMarketProduct.superMarket.createDate desc", new Object[]{employeeId,companyId,taskId,0}, false, true, false, 0, -1);
		  List<SuperMarket> list2=new ArrayList<SuperMarket>();
		  for(Object[] obj : list){
			  SuperMarket superMarket=new SuperMarket();
			  superMarket.setId(Long.parseLong(obj[0].toString()));
			  superMarket.setName((String)obj[1]);
			  list2.add(superMarket);
		  }
		return list2;
	}

	@Override
	public List<Brand> branListFromTaskAndCompany(long taskId,
			Long superMarketId, long employeeId) {
		// TODO Auto-generated method stub
		List<Object[]> list= (List<Object[]>)daoImpl.findListBySql("select taskBrand.brand.id,taskBrand.brand.name from  TaskProductEmployee where employee.id=? and superMarketProduct.superMarket.id=? and taskBrand.task.id=? and del=? and employee.del=0  group by taskBrand.brand.id order by taskBrand.brand.id desc", new Object[]{employeeId,superMarketId,taskId,0}, false, true, false, 0, -1);
		  List<Brand> list2=new ArrayList<Brand>();
		  for(Object[] obj : list){
			  Brand brand=new Brand();
			  brand.setId(Long.parseLong(obj[0].toString()));
			  brand.setName((String)obj[1]);
			  list2.add(brand);
		  }
		return list2;
	}

	@Override
	public List<Object> productlistOfSuperMarket(long taskId,
			long superMarketId, long brandId, long employeeId) {
		// TODO Auto-generated method stub
		List<Object[]> list= (List<Object[]>)daoImpl.findListBySql("select id,superMarketProduct.storecode,superMarketProduct.price,superMarketProduct.product.barcode,superMarketProduct.product.name,superMarketProduct.product.xiangGui,superMarketProduct.product.pinLei from  TaskProductEmployee where employee.id=? and superMarketProduct.superMarket.id=? and taskBrand.brand.id=?  and taskBrand.task.id=? and del=? and employee.del=0  order by id desc", new Object[]{employeeId,superMarketId,brandId,taskId,0}, false, true, false, 0, -1);
		  List<Object> list2=new ArrayList<Object>();
		  for(Object[] obj : list){
			  Map<String, Object> map=new HashMap<String, Object>();
			  map.put("taskSuperMarKetEmployeeId", obj[0]);
			  map.put("storecode", obj[1]);
			  map.put("price", obj[2]);
			  map.put("barcode", obj[3]);
			  map.put("name", obj[4]);
			  map.put("xianggui", obj[5]);
			  map.put("pinLei", obj[6]);
			  list2.add(map);
		  }
		return list2;
	}

	@Override
	public List<ChangGui> addChangGui(List<ChangGui> changGuis) {
		// TODO Auto-generated method stub
		List<ChangGui>  list=new ArrayList<ChangGui>();
		try{
		for(ChangGui changGui:changGuis){
			List<ChangGui> tpes=(List<ChangGui>)daoImpl.findListBySql("from ChangGui where taskProductEmployee.id=?",new Object[]{changGui.getTaskProductEmployee().getId()},false, true, false, 0, 1);
			if (tpes!=null&&tpes.size()>0) {
				ChangGui temp=tpes.get(0); 
				temp.setChenlie(changGui.getChenlie());
				temp.setFenxiao(changGui.getFenxiao());
				temp.setPrice(changGui.getPrice());
				temp.setStock(changGui.getStock());
				changGui=temp;
				//temp.setTaskProductEmployee(null);
				//daoImpl.deleteDomain(ChangGui.class, temp.getId());         
			}
			list.add(daoImpl.saveOrUpdateDomain(changGui)); 
			 
		 }
		}catch(Exception e){
			LogFactory.getDefaultLog().error(e.getLocalizedMessage(), LogName.API);
			return null;
		}
		return list;
	}

	@Override
	public TaskProductEmployee findTaskProductEmployeeEmployee(
			long taskProductEmployeeId) {
		return daoImpl.getDomain(TaskProductEmployee.class, taskProductEmployeeId);
	}

	@Override
	public List<Object> addHelpSale(List<Map<String, String>> param) {
		// TODO Auto-generated method stub
		List<Object>  list=new ArrayList<Object>();
		try{
		for(Map<String, String> map:param){
			List<HelpSale> tpes=(List<HelpSale>)daoImpl.findListBySql("from HelpSale where taskProductEmployee.id=?",new Object[]{Long.parseLong(map.get("taskProductEmployeeId"))},false, true, false, 0, 1);
			HelpSale helpSale;
			if (tpes!=null&&tpes.size()>0) {
				helpSale=tpes.get(0);
			}else{
				helpSale=new HelpSale();
				helpSale.setCreateDate(new Timestamp(System.currentTimeMillis()));
				helpSale.setDel(0);
				helpSale.setTaskProductEmployee( daoImpl.getDomain(TaskProductEmployee.class, Long.parseLong(map.get("taskProductEmployeeId"))));
			}
			helpSale.setChenlie(map.get("chenlie"));
			helpSale.setDuitou(map.get("duitou"));
			helpSale.setFenxiao("fenxiao");
			helpSale.setHaibao(map.get("haibao"));
			helpSale.setPrice(map.get("price"));
			helpSale.setStock(map.get("stock"));
			helpSale.setZhuangui(map.get("zhuangui"));
			helpSale.setZhuxiao(map.get("zhuxiao"));
			list.add(daoImpl.saveOrUpdateDomain(helpSale));  
		 }
		}catch(Exception e){
			LogFactory.getDefaultLog().error(e.getLocalizedMessage(), LogName.API);
			return null;
		}
		return list;
	}

	@Override
	public List<Task> findTaskByEid(long employeeId) {
		String sql = "from TaskProductEmployee where del!=1 and employee.id=? and taskBrand.task.endDate>?";
		sql += " group by taskBrand.task.id";
		try {
			List<TaskProductEmployee> tpes = (List<TaskProductEmployee>)daoImpl.findListBySql(sql, new Object[]{employeeId,new Timestamp(System.currentTimeMillis())},false, true, false, -1, -1);
			List<Task> tasks = new ArrayList<Task>();
			for (int i = 0; i < tpes.size(); i++) {
				tasks.add(tpes.get(i).getTaskBrand().getTask());
			}
			return tasks;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	public List<TaskProductEmployee> findTaskProductEmployeeByTaskEmployee(long taskId,long employeeId) {
		String sql = "from TaskProductEmployee where del!=1 and employee.id=? and taskBrand.task.id=?";
		try {
			List<TaskProductEmployee> taskProductEmployees = (List<TaskProductEmployee>)daoImpl.findListBySql(sql, new Object[]{employeeId,taskId},false, true, false, -1, -1);
			return taskProductEmployees;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
